//
//  HomeTableViewController.swift
//  0729FirstProgramMicroblog
//
//  Created by ding on 15/7/29.
//  Copyright © 2015年 ding. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {
    
    let reusedIdentifier = "status_cell"
    
    var statuses: [DINGMicroblogStatus]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        refreshControl = DINGRefreshControl()
        
        refreshControl?.addTarget(self, action: "startRefresh", forControlEvents: UIControlEvents.ValueChanged)
        
        
        
        if UserAcountInfo.userAccountInfo == nil {
            viewForVistor?.setupViewInfo(true, message: "关注一些人，回这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon")
            return
        }
        
        tableView.registerClass(DINGNormalStatusCell.self, forCellReuseIdentifier: DINGStatusCellReusedIdentifier.NormalCell.rawValue)
        tableView.registerClass(DINGForwardStatusCell.self, forCellReuseIdentifier: DINGStatusCellReusedIdentifier.ForwardCell.rawValue)

//        tableView.rowHeight = 320
        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        loadStatuses()
    
    }
    
    func startRefresh() {
        refreshControl?.beginRefreshing()
    }
    
    
    
    private func loadStatuses() {
        DINGMicroblogStatus.loadMicroblog { (statusResult, error) -> () in
            if error != nil {
                print(error)
            }
            self.statuses = statusResult
        }
    }
    
    //MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(DINGStatusCellReusedIdentifier.getCellIdentifier(status)!, forIndexPath: indexPath) as! DINGStatusCell
        
        print("xianshineirong --------")
        cell.statuses = status

        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        
        if let statusH = status.rowHeight {
//            print("返回缓存行高")
            return statusH
        }
        // 计算并缓存行高
//        print("计算行高")
        let cell = tableView.dequeueReusableCellWithIdentifier(DINGStatusCellReusedIdentifier.getCellIdentifier(status)!) as! DINGStatusCell

        status.rowHeight = cell.getCellHeight(status)
        
        return status.rowHeight!
    }

}